import 'package:bigegg/common/log/xmm_logcat.dart';
import 'package:bigegg/data/repository/xmm_remote_repository.dart';
import 'package:bigegg/entity/xmm_coin_goods.dart';
import 'package:bigegg/global/user/xmm_account_manager.dart';
import 'package:bigegg/utils/xmm_apply_pay_utils.dart';
import 'package:bigegg/utils/xmm_toast_util.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

import '../../common/get/controller/xmm_base_controller.dart';
import '../../common/log/xmm_log.dart';

class XmmShoppingCoinController extends XmmBaseGetxController {
  final remoteRepository = XmmRemoteRepository();

  final coinGoodsList = <XmmCoinGoods>[].obs;

  void getCoinGoodsList() {
    remoteRepository
        .getCoinGoodsList()
        .then((value) => coinGoodsList.value = value);
  }

  void applyPay(XmmCoinGoods coinGoods) async {
    try {
      EasyLoading.show();
      XmmLogManger().putLog(XmmLogType.clickEvent, {'page': XmmLogPages.pageCreateOrder});
      var goodsCode = coinGoods.code ?? "";
      var resp = await remoteRepository.createCoinRecharge(goodsCode);
      if (resp.success) {
        await XmmApplyPayUtils().applePay(resp.data, callback: (code) {
          XmmAccountManager.instance.user.availableCoins += (coinGoods.exchangeCoin ?? 0);
          XmmAccountManager.instance.updateUserInfo();
          XmmToastUtils.show('Purchase Success');
        });
      } else {
        XmmToastUtils.show('Recharge Failed, please try again.');
      }
    } catch (e, s) {
      XmmToastUtils.show('Recharge failed, please try again.');
      XmmXLogcat.e('$e  $s');
    } finally {
      EasyLoading.dismiss();
    }
  }
}
